<template>
  <div class="padding flex direction-column width-100 height-100">
    <div class="search-form">
      <el-form inline>
        <el-form-item>
          <el-radio-group v-model="type">
            <el-radio :label="1">季报</el-radio>
            <el-radio :label="2">年报</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年份" style="margin-left: 40px;">
          <el-date-picker type="year" :editable="false" :clearable="false" v-model="year" value="yyyy" value-format="yyyy" :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>
        <el-form-item v-if="type === 1" label="季度">
          <el-select v-model="quarter">
            <el-option v-for="option in options" :key="option.value" v-bind="option"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form inline>
        <el-form-item label="所属区域">
          <area-picker v-model="areaCode"></area-picker>
        </el-form-item>
        <el-form-item label="企业名称">
          <el-select v-model="tenantId" filterable clearable>
            <el-option v-for="enterprise in enterpriseList" :key="enterprise.id" :label="enterprise.name"
              :value="enterprise.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年能耗等级">
          <dictionary-picker v-model="energyConsumptionLevel" dic-code="NENG_HAO_SHUI_PING"></dictionary-picker>
        </el-form-item>
        <el-form-item label="上报状态">
          <el-select v-model="reportState" filterable clearable>
            <el-option v-for="item in reportStateList" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="flex-1 overflow-auto dark-table-wrapper">
      <el-table
      v-loading="loading"  :data="lists" height="100%"
      :header-cell-style="{
        color: 'white',
        backgroundColor: themeColor
      }">
        <div slot="empty" class="empty-lists">
          <i class="i-custom:search"></i>
          <span class="empty-text">暂无数据</span>
        </div>
        <el-table-column label="企业名称" prop="enterpriseName"></el-table-column>
        <el-table-column label="上报状态" prop="stateName"></el-table-column>
        <el-table-column label="备注" prop="illustrate"></el-table-column>
        <el-table-column label="操作" fixed="right" :width="300">
          <template #default="{row}">
            <el-button v-if="getButtons(row.state).includes(1)" type="primary" size="mini" @click="clickView(row)">查看</el-button>
            <el-button v-if="getButtons(row.state).includes(2)" type="primary" size="mini" @click="clickCheck(row)">审核</el-button>
            <el-button v-if="getButtons(row.state).includes(3)" type="primary" size="mini" @click="clickViewHistory(row)">历史操作</el-button>
            <quick-download-button :fn="() => clickDownloadByEnterprise(row)"></quick-download-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      class="pagination" layout="total,prev,pager,next" background
      :current-page.sync="pagination.pageNumber" :page-size="pagination.pageSize"
      :total="pagination.total"
      @current-change="getTableData"
      @size-change="getTableData"
    ></el-pagination>

    <!-- 查看操作历史 -->
    <report-history-modal
      v-if="selectEnterpriseId"
      ref="reportHistoryModal"
      :year="year"
      :quarter="quarter"
      :enterprise-id="selectEnterpriseId"
      :is-year="type === 2"
    ></report-history-modal>

    <!-- 报表对话框 -->
    <div v-if="showTableAccount" class="padding table-account-details">
      <div class="flex items-center width-100">
        <el-button class="flex-shrink-0" style="width: 32px;height:32px;" type="primary" icon="el-icon-back" circle @click="back(true)"></el-button>
        <el-tabs v-model="selectTabName"
          class="flex-1" style="margin-left: 30px;margin-right:30px;"
          @tab-click="handleTableAccountIdClicked"
        >
          <el-tab-pane v-for="tab in myTabs" :key="tab.id" :label="tab.name" :name="'s_'+tab.id"></el-tab-pane>
        </el-tabs>
        <div v-if="isCheck" style="">
          <el-button v-if="!hasPassed" type="success" @click="resolve">通过</el-button>
          <el-button type="danger" @click="reject">退回</el-button>
        </div>
      </div>
      <component
        :is="tableComponent"
        ref="quarterlyAccountTable"
        :year="year" :quarter="quarter"
        :columns="tableColumns" :name="tableName" :t-id="+tableAccountId"
        :enterprise-id="selectEnterpriseId" :enterprise-name="selectEnterpriseName"
        :readonly="readonly" :show-line-number="false"
        :is-government="true"
        :small_numeral_name="small_numeral_name"
        :first_of_five_year_plan="first_of_five_year_plan"
      >
        <template #title="{ title, seriesNo }">
          <div class="flex align-center position-relative">
            <h2 :title="title" class="margin-horizontal-auto text-truncate"
              :style="'max-width: calc(100% - '+titleWidth+'px);font-weight: normal;'">
              {{title}}
              <small v-if="seriesNo">（{{seriesNo}}）</small>
            </h2>
            <el-button type="primary" @click="export_excel_report_report">导出</el-button>
          </div>
        </template>
      </component>
    </div>
  </div>
</template>

<script>
import MixinTableLists from './mixin-table-lists'
import MixinReportTables from './mixin-report-tables'
import MixinReportAudit from './mixin-report-audit'
import {
  TABLE_UNDER_REPORT_TEXT,
  TABLE_REPORTED_TEXT,
  TABLE_RESOLVED_TEXT,
  TABLE_REJECTED_TEXT,
  // TABLE_REPORTED,
  // TABLE_UNDER_REPORT,
  REPORT_AUDIT_STATUS_OPTIONS,
  E_UNDER_REPORT,
  E_RESOLVED,
} from '@/config'
import AreaPicker from '@/components/area-picker'
import DictionaryPicker from '@/components/dictionary-picker'
import ReportHistoryModal from './components/report-history-modal'
import QuarterlyAccountDetails from '@/mixins/quarterly-account-details-new'
import MixinReportReportExportExcel from '@/mixins/mixin-report-report-export-excel'

export default {
  name: 'report-report-audit',
  components: {
    AreaPicker,
    DictionaryPicker,
    ReportHistoryModal,
    QuickDownloadButton: {
      props: {
        fn: {
          type: Function,
          default () {
            return () => {}
          }
        }
      },
      data () {
        return {
          downloading: false,
        }
      },
      render (h) {
        return (
          this.downloading
            ? <el-button type="primary" size="mini" icon="el-icon-loading"></el-button>
            : <el-button type="primary" size="mini" onClick={this.download}>导出</el-button>
        )
      },
      methods: {
        download () {
          this.downloading = true;
          this.fn().finally(() => {
            this.downloading = false;
          })
        }
      }
    }
  },
  mixins: [
    MixinTableLists, MixinReportTables,
    MixinReportAudit, QuarterlyAccountDetails,
    MixinReportReportExportExcel
  ],
  data() {
    return {
      type: 1,
      year: this.$dayjs().format('YYYY'),
      quarter: this.$dayjs().quarter(),
      options: [
        { value: 1, label: '第一季度' },
        { value: 2, label: '第二季度' },
        { value: 3, label: '第三季度' },
        { value: 4, label: '第四季度' }
      ],

      selectEnterpriseId: null,
      selectEnterpriseName: '',
      selectTabName: null,
      isCheck: false,

      hasPassed: false,

      pagination: {
        pageNumber: 1,
        pageSize: 20,
        total: 0
      },

      areaCode: '',
      tenantId: '',
      energyConsumptionLevel: '',
      reportState: '',
      reportStateList: REPORT_AUDIT_STATUS_OPTIONS,
    }
  },
  computed: {
    isYear () {
      return this.type === 2
    },
    themeColor () {
      return this.$store.state.user.theme;
    },
    userInfo () {
      return this.$store.state.user.userInfo || {}
    },
    enterpriseList() {
      return this.$store.state.energyEnterpriseList
    },
    titleWidth () {
      let w = 200;
      if (this.showButton) {
        w += 300
      }
      if (this.useAutoSave) {
        w += 100
      }
      return w
    }
  },
  mounted() {
    this.$store.dispatch('GET_ENTERPRISE_LIST')
    this.getTableData();
  },
  watch: {
    type: {
      handler (val) {
        // 2-年度，对应 quarter = 5
        this.quarter = val === 1 ? this.$dayjs().quarter() : 5
      },
      immediate: true
    },
    selectTabName: {
      handler (val) {
        if (val) {
          this.tableAccountId = +val.split('_')[1]
        }
      },
      immediate: true,
    },
    year () {
      this.search()
    },
    quarter () {
      this.search()
    },
    showTableAccount (val) {
      if (val === false) {
        this.search()
      }
    }
  },
  methods: {
    search() {
      this.pagination.pageNumber = 1
      this.$nextTick(() => {
        this.getTableData()
      })
    },
    statusText(s) {
      // ’‘、未上报、未上报、已上报、已通过、已退回
      const status = ['', TABLE_UNDER_REPORT_TEXT, TABLE_UNDER_REPORT_TEXT, TABLE_REPORTED_TEXT, TABLE_RESOLVED_TEXT, TABLE_REJECTED_TEXT]
      return status[s] || status[0]
    },
    getTableData () {
      const params = {
        enterpriseId: this.tenantId || '',
        districtBelong: this.areaCode,
        energyConsumptionLevel: this.energyConsumptionLevel,
        state: this.reportState,
        pageNumber: this.pagination.pageNumber,
        pageSize: this.pagination.pageSize,
        year: this.year,
        quarter: this.quarter
      }
      this.getLists(params)
    },
    clickViewHistory (row) {
      this.selectEnterpriseId = row.enterpriseId;
      this.$nextTick(() => {
        this.$refs.reportHistoryModal.open();
      })
    },
    async clickView (row) {
      this.selectEnterpriseId = row.enterpriseId + '';
      this.selectEnterpriseName = row.enterpriseName;

      this.isCheck = false;

      if (row.state === E_UNDER_REPORT) {
        this.$message.warning('该企业未上报数据');
        return false
      }

      await this.queryTabs(this.selectEnterpriseId, this.year, this.quarter)

      const tableId = this.myTabs[0].id
      this.selectTabName = 's_' + tableId;
      if (tableId) {
        this.edit(tableId)
      }
    },
    handleTableAccountIdClicked (tabInstance) {
      const tabName = tabInstance.name;
      if (tabName) {
        const tableId = +tabName.split('_')[1]
        this.edit(tableId)
      }
    },
    async clickCheck (row) {
      this.selectEnterpriseId = row.enterpriseId + '';
      this.selectEnterpriseName = row.enterpriseName;

      this.isCheck = true;
      this.hasPassed = row.state === E_RESOLVED;

      await this.queryTabs(this.selectEnterpriseId, this.year, this.quarter)

      const tableId = this.myTabs[0].id
      this.selectTabName = 's_' + tableId;
      if (tableId) {
        this.edit(tableId)
      }
    },
    clickDownloadByEnterprise (row) {
      try {
        const { year, quarter } = this
        const enterpriseId = row.enterpriseId
        return this.export_excel_multiple_sheets(year, quarter, row.enterpriseId)
      } catch (e) {
        console.warn(e);
        return Promise.resolve()
      }
    }
  }
}
</script>
